package com.matriq.cloudmanager;

import java.util.List;

import com.matriq.cloudmanager.R;
import com.matriq.cloudmanager.dialog.ConfirmDialog;
import com.matriq.cloudmanager.entity.CourseCommentSubject;
import com.matriq.cloudmanager.service.AccountService;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import net.lgpage.activity.BaseActivity;
import net.lgpage.dialog.DialogListener;
import net.lgpage.http.ExceptionAsyncTask;
import net.lgpage.http.HttpMsg;
import net.lgpage.http.SwipeRefeshAsyncTask;
import net.lgpage.util.Checker.StringUtils;
import net.lgpage.util.Cleaner;
import net.lgpage.util.RecyclerViewFooterAdapter;

public class CourseEvalActivity extends BaseActivity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_course_eval);
		setViews();
		setEvents();
		loadData();
	}

	android.support.v4.widget.SwipeRefreshLayout srl;
	android.support.v7.widget.RecyclerView rcy_course_eval;
	TextView tv_title;
	ImageButton ll_back;
	//Button bt_confirm;
	LinearLayout ll_nothing;
	TextView tv_nothing;

	LinearLayoutManager ll_mng;
	private void setViews() {
		srl = (android.support.v4.widget.SwipeRefreshLayout) this.findViewById(R.id.srl);
		rcy_course_eval = (android.support.v7.widget.RecyclerView) this.findViewById(R.id.rcy_course_eval);
		RcyAdp adp = new RcyAdp();
		rcy_adp = new RecyclerViewFooterAdapter(adp);
		ll_mng = new LinearLayoutManager(this);
		rcy_course_eval.setLayoutManager(ll_mng);
		rcy_course_eval.setAdapter(rcy_adp);
		tv_title = (TextView) this.findViewById(R.id.tv_title);
		ll_back = (ImageButton) this.findViewById(R.id.ll_back);
		//bt_confirm = (Button) this.findViewById(R.id.bt_confirm);
		ll_nothing = (LinearLayout) this.findViewById(R.id.ll_nothing);
		tv_nothing = (TextView) this.findViewById(R.id.tv_nothing);
	}

	private void setEvents() {
		srl.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				refeshRcyList();
			}
		});
		setNotingEvents();
	}

	Object obj;

	public void setData(Object obj) {
		this.obj = obj;
		tv_title.setText(null);
		tv_nothing.setText(null);
	}
	
	

	private class RcyViewHolder extends RecyclerView.ViewHolder {
		LinearLayout ll_score;
		SeekBar sb;
		TextView tv[] = new TextView[2];
		EditText et;
		
		public RcyViewHolder(View view) {
			super(view);
		}
	}
	private class RcyFooterViewHolder extends RcyViewHolder{

		Button bt_confirm;
		public RcyFooterViewHolder(View view) {
			super(view);
			bt_confirm = (Button) view.findViewById(R.id.bt_confirm);
			if (type == 1) {
				bt_confirm.setVisibility(View.VISIBLE);
				bt_confirm.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (checkEts()) {
							ConfirmDialog dg = new ConfirmDialog(getActivity());
							dg.setData("评价后不可修改，是否继续提交？");
							dg.setListener(new DialogListener() {

								@Override
								public void onDialogExecute(Object... obj) {
									putObj();
								}
							});
							dg.show();
						}
					}
				});
			} else {
				bt_confirm.setVisibility(View.GONE);
			}
		}
		
	}
	RecyclerViewFooterAdapter rcy_adp;

	class RcyAdp extends RecyclerView.Adapter<RcyViewHolder> {

		LayoutParams lp;

		@Override
		public int getItemCount() {
			if (rcylist == null)
				return 0;
			return rcylist.size();
		}
		
		public LayoutParams getLp() {
			return lp;
		}

		public RcyAdp() {
			super();
			lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		}

		@Override
		public void onBindViewHolder(final RcyViewHolder h, final int position) {
			final CourseCommentSubject obj = rcylist.get(position);
			h.tv[0].setText(obj.getTitle());
			if ("1".equals(obj.getType())) {
				h.et.setVisibility(View.GONE);
				h.ll_score.setVisibility(View.VISIBLE);
				int score = 0;
				int progress = 0;
				try {
					score = Integer.parseInt(obj.getScore());
				} catch (NumberFormatException e) {
					score = 0;
				}
				try {
					progress = Integer.parseInt(obj.getGoal());
				} catch (NumberFormatException e) {
					progress = score;
					obj.setGoal(String.valueOf(progress));
				}
				h.sb.setMax(score);
				h.sb.setProgress(progress);
				h.tv[1].setText("你的评分:" + progress + "/" + score);
				h.sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

					@Override
					public void onStopTrackingTouch(SeekBar seekBar) {

					}

					@Override
					public void onStartTrackingTouch(SeekBar seekBar) {

					}

					@Override
					public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
						obj.setGoal(String.valueOf(progress));
						h.tv[1].setText("你的评分:" + progress + "/" + seekBar.getMax());
					}
				});
			} else if ("2".equals(obj.getType())) {
				h.et.setText(obj.getGoal());
				h.et.setVisibility(View.VISIBLE);
				h.et.addTextChangedListener(new TextWatcher() {

					@Override
					public void onTextChanged(CharSequence s, int start, int before, int count) {
						obj.setGoal(s.toString());
					}

					@Override
					public void beforeTextChanged(CharSequence s, int start, int count, int after) {

					}

					@Override
					public void afterTextChanged(Editable s) {

					}
				});
				h.ll_score.setVisibility(View.GONE);

			}
			if (type == 2) {
				h.et.setEnabled(false);
				h.et.setHint("");
				h.sb.setEnabled(false);
				h.sb.setVisibility(View.GONE);
				h.et.setMinLines(2);
				h.et.setBackgroundResource(R.color.transparent);
			} else {
				h.et.setEnabled(true);
				h.et.setHint("请输入你的建议");
				h.sb.setEnabled(true);
				h.sb.setVisibility(View.VISIBLE);
			}
		}

		@Override
		public RcyViewHolder onCreateViewHolder(ViewGroup vgp, final int position) {
			View cv = getLayoutInflater().inflate(R.layout.rcy_course_eval, null);
			cv.setLayoutParams(lp);
			RcyViewHolder h = new RcyViewHolder(cv);
			h.ll_score = (LinearLayout) cv.findViewById(R.id.ll_score);
			h.sb = (SeekBar) cv.findViewById(R.id.sb);
			
			h.tv[0] = (TextView) cv.findViewById(R.id.tv0);
			h.tv[1] = (TextView) cv.findViewById(R.id.tv1);
			h.et = (EditText) cv.findViewById(R.id.et);
			return h;
		}

	}

	private boolean checkEts() {
		if (rcylist == null)
			return false;
		for (int i = 0; i < rcylist.size(); i++) {
			CourseCommentSubject obj = rcylist.get(i);
			if (StringUtils.isEmpty(obj.getGoal())) {
				if ("1".equals(obj.getType())) {
					toast("第" + (i + 1) + "题尚未选择");
					return false;
				} else {
					obj.setGoal("");
					// toast("第"+(i+1)+"题尚未填写");
				}
			}else if("0".equals(obj.getGoal())&&"1".equals(obj.getType())){
				toast("第" + (i + 1) + "题尚未选择,所选分值需大于0");
				return false;
			}
		}
		return true;
	}

	List<CourseCommentSubject> rcylist;
	RcyListTask rcylistTask;

	public void refeshRcyList() {
		if (rcylistTask != null) {
			rcylistTask.cancel(true);
		}
		rcylistTask = new RcyListTask(this);
		rcylistTask.setSwipeLayout(srl);
		rcylistTask.execute();
	}

	private class RcyListTask extends SwipeRefeshAsyncTask<List<CourseCommentSubject>> {

		public RcyListTask(Context context) {
			super(context);
		}

		@Override
		public List<CourseCommentSubject> doInBackgroundX(String... params) throws Exception {
			if (type == 1) {
				return AccountService.getService().course_comment_p(courseid);
			} else {
				return AccountService.getService().course_comment_c(courseid);
			}
		}

		@Override
		public void onPostExecuteX(List<CourseCommentSubject> result) {
			if (result == null) {
				return;
			} else {
				rcylist = result;
				if (type == 1) {
					for (int i = 0; i < rcylist.size(); i++) {
						CourseCommentSubject ccs = rcylist.get(i);
						if("1".equals(ccs.getType())){
							ccs.setGoal("0");
						}else{
							ccs.setGoal("");
						}
					}
				}
				checkListNoting();
				rcy_adp.notifyDataSetChanged();
				srl.setEnabled(false);
				rcy_adp.setFooterView(new RcyFooterViewHolder(getLayoutInflater().inflate(R.layout.rcyfooter_eval,null)));
				rcy_adp.getFooterViewHolder().itemView.setLayoutParams(((RcyAdp)rcy_adp.getAdp()).getLp());
			}
		}
	}

	ObjTask objTask;

	public void putObj() {
		if (objTask != null) {
			objTask.cancel(true);
		}
		objTask = new ObjTask(this);
		objTask.execute();
	}

	private class ObjTask extends ExceptionAsyncTask<HttpMsg> {

		public ObjTask(Context context) {
			super(context);
		}

		@Override
		public HttpMsg doInBackgroundX(String... params) throws Exception {
			return AccountService.getService().comment_commit(courseid, rcylist);
		}

		@Override
		public void onPostExecuteX(HttpMsg result) {
			if (result == null) {
				return;
			} else {
				obj = result;
				getActivity().setResult(200);
				getActivity().finish();
			}
		}
	}

	String courseid;

	int type;

	private void loadData() {
		courseid = getIntent().getStringExtra("courseid");
		type = getIntent().getIntExtra("type", 1);
		
		refeshRcyList();
		
	}

	private void setNotingEvents() {
		ll_nothing.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				changeListState(false);
				refeshRcyList();
			}
		});
	}

	private void checkListNoting() {
		if (rcylist == null || rcylist.size() == 0) {
			changeListState(true);
		} else {
			changeListState(false);
		}
	}

	private void changeListState(boolean isnothing) {
		if (!isnothing) {
			ll_nothing.setVisibility(View.GONE);
			srl.setVisibility(View.VISIBLE);
		} else {
			ll_nothing.setVisibility(View.VISIBLE);
			srl.setVisibility(View.GONE);
		}
	}

	@Override
	public void onDestroy() {
		Cleaner.cleanTask(rcylistTask, objTask);
		super.onDestroy();
	}

}